<!-- 用例脚本模块，待重新设计 -->
<template>
  <div class="div_box">
    <div style="min-width: 1600px;">
      <!-- 页面布局：整体 -->
      <el-container style="border: 1px solid #eee">
        <!-- 页面布局：头部 -->
        <el-header style="background: #FFFFFF; border:1px solid #eeeeee; margin: 10px 10px 10px 10px; padding: 10px 20px;">
          <el-button size="mini" icon="el-icon-video-play" circle @click="localRun" />
          <el-button size="mini" icon="el-icon-document" circle @click="saveScript" />
          <el-button size="mini" icon="el-icon-refresh" circle @click="getOnTimeLog" />
        </el-header>
        <!-- 页面布局：内容 -->
        <el-container style="height: 700px;">
          <!-- 内容布局：侧边栏 -->
          <el-aside width="300px" style="background: #FFFFFF; border:1px solid #eeeeee; margin: 0 10px 0 10px;">
            <el-tree
              class="aside"
              :data="treeData"
              :props="defaultProps"
              node-key="id"
              :default-expanded-keys="defaultExpandedKeys"
              :draggable="draggable"
              :allow-drop="allowDrop"
              :allow-drag="allowDrag"
              :default-expand-all="true"
              @node-click="handleClick"
              @node-drag-start="handleDragStart"
              @node-expand="handleExpend"
              @node-collapse="handleCollapse"
              @node-contextmenu="handleReghtClick"
            >
              <span slot-scope="{ node, data }" class="custom-tree">
                <span :title="data.title" tabindex="0">
                  <svg-icon :icon-class="node.data.icon" />
                  <span :title="node.data.label" @dblclick="dblClickNode(node)">{{ node.data.label }}</span>
                </span>
              </span>
            </el-tree>
          </el-aside>
          <!-- 内容布局：主体 -->
          <el-main style="background: #FFFFFF; border:1px solid #eeeeee; margin: 0 10px 0 10px; padding: 10px 10px;">
            <!-- 脚本的文本视图 -->
            <div>
              <editor ref="textView" v-model="script" lang="java" theme="eclipse" width="100%" height="650px" :options="editorOptions" @init="editorInit" />
            </div>
          </el-main>
        </el-container>
        <!-- 页面布局：页尾 -->
        <el-footer style="background: #FFFFFF; border:1px solid #eeeeee; margin: 10px 10px 10px 10px; padding: 10px 20px; height: auto;">
          <ul>
            <li v-for="(log, index_1) in logList" :key="index_1">{{ log }}</li>
          </ul>
        </el-footer>
      </el-container>
    </div>
  </div>
</template>

<script>
import { searchDetail, saveScript, localRun, getOnTimeLog } from '@/api/auto/case.js'
import { getAllActions } from '@/api/auto/action.js'
export default {
  name: 'AutoCaseScript',
  components: {
    editor: require('vue2-ace-editor')
  },
  data() {
    return {
      treeData: [
        { id: 0, label: '断言', icon: 'love-flowers', root: true, class: 'super', method: 'doAssert', params: '(boolean flag, String desc);', return: 'null' },
        { id: 1, label: '原子操作', icon: 'folder-close', children: [], root: true },
        { id: 2, label: '逻辑操作', icon: 'folder-close', children: [], root: true }
      ],
      // 前端页面上的根节点
      defaultProps: { children: 'children', label: 'label' },
      defaultExpandedKeys: [0], // 默认展开节点
      draggable: true,
      caseDetail: null,
      script:
`package PACKAGE_NAME;

import scripts.ScriptTemplate;

/**
 * 作者：
 * 日期：
 * 备注：
 */
public class CLASS_NAME extends ScriptTemplate {

    @Override
    public void beforeTest() {
        // 前置操作
    }

    @Override
    public void onTest() {
        // 测试步骤
    }

    @Override
    public void afterTest() {
        // 后置操作
    }

    @Override
    public void onTestFail() {
        try {
            afterTest();
        } catch (Exception e) {
            // TOOD 自行处理异常
        }
    }

}`,
      editorOptions: { enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true, enableEmmet: true, useElasticTabstops: true },
      sid: null,
      logList: []
    }
  },
  created() {
    this.getTreeData()
    this.getOldScript()
  },
  methods: {
    test() {
      this.$refs.textView.editor.insert('Something cool\n')
    },
    getTreeData() {
      // 获取原子操作节点
      getAllActions().then(respnose => {
        if (respnose && respnose.code === 200) {
          const { data } = respnose
          this.treeData[1].children = data
        } else {
          this.$message.error(respnose.message)
          this.treeData[1].children = []
        }
      })
    },
    editorInit() {
      require('brace/ext/language_tools') // language extension prerequsite...
      require('brace/mode/json')
      require('brace/mode/javascript') // language
      require('brace/mode/java') // language
      require('brace/mode/less')
      require('brace/theme/eclipse')
      require('brace/snippets/javascript') // snippet
    },
    getOldScript() {
      searchDetail(this.$route.params.caseId).then(respnose => {
        if (respnose && respnose.code === 200) {
          const { data } = respnose
          this.caseDetail = data
          if (data.script && data.script !== 'NA') {
            this.script = data.script
          } else {
            this.script = this.script.replace('CLASS_NAME', data.num).replace('PACKAGE_NAME', 'suibian')
          }
        } else {
          this.$message.error(respnose.message)
          this.caseDetail = null
        }
      })
    },
    // 是否允许放下
    allowDrop(draggingNode, dropNode, type) {
      return false
    },
    // 是否允许托起
    allowDrag(draggingNode) {
      return !draggingNode.data.isFolder
    },
    handleExpend(data) {
      data.icon = 'folder-open'
    },
    handleCollapse(data) {
      data.icon = 'folder-close'
    },
    handleClick(data) {},
    dblClickNode(node) {
      if (node.data.isFolder) {
        return
      }
      let currentRow = this.$refs.textView.editor.selection.getCursor().row
      const currentCol = this.$refs.textView.editor.selection.getCursor().column

      console.info(currentRow, currentCol)

      let flag = false
      // 如果返回值需要导包，先跳转到第二行导包
      if (node.data.return.indexOf('.') !== -1 && this.script.indexOf(node.data.return.split(' ')[0]) === -1) {
        flag = true
        currentRow = currentRow + 2
        this.$refs.textView.editor.gotoLine(3)
        this.$refs.textView.editor.insert('import ' + node.data.return.split(' ')[0] + ';\n')
        this.$refs.textView.editor.gotoLine(currentRow)
      }

      const classSplit = node.data.class.split('.')
      const classPackage = classSplit.join('.')
      const className = classSplit.pop()

      if (node.data.class.indexOf('.') !== -1) {
        // 如果当前AW需要导包，先跳转到第二行导包
        if (this.script.indexOf(classPackage) === -1) {
          if (flag) {
            currentRow = currentRow + 1
          } else {
            currentRow = currentRow + 2
          }
          this.$refs.textView.editor.gotoLine(3)
          this.$refs.textView.editor.insert('import ' + classPackage + ';\n')
          this.$refs.textView.editor.gotoLine(currentRow)
        }
      }

      if (this.$refs.textView.editor.selection.getCursor().column === 0) {
        this.$refs.textView.editor.insert(new Array(currentCol + 1).join(' '))
      }

      if (node.data.return !== 'null') {
        this.$refs.textView.editor.insert(node.data.return.split('.').pop() + ' = ' + className + '.' + node.data.method + node.data.params + '\n\n')
      } else {
        this.$refs.textView.editor.insert(className + '.' + node.data.method + node.data.params + '\n\n')
      }
      this.$refs.textView.editor.insert(new Array(currentCol + 1).join(' '))
    },
    handleDragStart(node, ev) {
      this.dblClickNode(node)
    },
    handleDragEnd(draggingNode, dropNode, dropType, ev) {},
    handleReghtClick(event, data, node, self) {},
    localRun() {
      this.$prompt('默认为：http://127.0.0.1:18091', '执行机地址', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (value === null) {
          value = 'http://127.0.0.1:18091'
        }
        localRun(value, {
          'author': 'todo',
          'caseNum': this.caseDetail.num,
          'caseName': this.caseDetail.name,
          'caseId': this.caseDetail.id,
          'script': this.script
        }).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.sid = respnose.sid
          } else {
            this.$message.error(respnose.message)
            this.sid = null
          }
        })
      }).catch(() => {})
    },
    getOnTimeLog() {
      if (this.sid) {
        getOnTimeLog(this.sid).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.logList = respnose.logList
          } else {
            this.$message.error(respnose.message)
          }
        })
      } else {
        this.$message('未执行')
      }
    },
    saveScript() {
      saveScript(this.$route.params.caseId, this.script).then(respnose => {
        if (respnose && respnose.code === 200) {
          this.$message.success(respnose.message)
        } else {
          this.$message.error(respnose.message)
        }
      })
    }
  }
}
</script>

<style scoped="scoped">
.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.aside {
  float: left;
  width: 100%;
  height: 100%;
  /* 控制自动出现滚动条 */
  overflow-y: auto;
  overflow-x: auto;
}

.el-collapse {
  margin-bottom: 20px;
  margin-top: 20px;
}

.el-collapse-item {
  margin-bottom: 10px;
}

.line-out {
  display: block;
  height: 1px;
  width: 100%;
  margin: 24px 0;
  background-color: #DCDFE6;
  position: relative;
}

.line-in {
  left: 50%;
  /* -webkit-transform: translateX(-50%) translateY(-50%); */
  transform: translateX(-50%) translateY(-50%);

  position: absolute;
  background-color: #FFF;
  padding: 0 20px;
  color: #303133;

  font-weight: 500;
  font-size: 14px;
}

.textTitle {
  margin-left: 10px;
}

.el-card__body {
  padding: 0;
}

.el-card {
 margin-bottom: 10px;
}

.input-title {
  padding-left: 0px;
  border: none;
  font-weight: bold;
}

.el-table .warning-row {
  color: #FF0000;
  text-decoration: line-through;
}
.div_box {
  border: 1px solid #eee;
  padding-left: 15px;
  padding-right: 15px;
  padding-top: 15px;
  padding-bottom: 10px;
  margin-top: 10px;
  margin-bottom: 10px;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: auto;
}
</style>
